package com.framework.modules.job.task;


import com.framework.entity.sys.SysAgent;
import com.framework.entity.sys.SysAgentGrade;
import com.framework.entity.sys.SysDeptEntity;
import com.framework.entity.sys.SysLvRate;
import com.framework.modules.sys.service.SysDeptService;
import com.framework.service.AgentGradeService;
import com.framework.service.AgentService;
import com.framework.service.LvRateService;
import com.framework.service.TransactionInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 功能描述: 每月第一天更新合伙人等级信息
 *
 * @author wq
 * @date 2018/11/12
 */
@Component("updateAgentLevelTask")
public class UpdateAgentLevelTask {

    @Autowired
    private AgentService agentService;

    @Autowired
    private LvRateService sysLevelRateService;

    @Autowired
    private AgentGradeService agentGradeService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private TransactionInfoService transactionInfoService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 等级信息判断金额所需要放大的倍数 :1万倍 string 入参不会失真
     */
    private static final BigDecimal MULTINUM = new BigDecimal("10000");


    private void updateAgentLevelByDeptId() {

        List<SysDeptEntity> list = sysDeptService.selectList(null);
        logger.info("===============更新合伙人等级定时器开==============");

        List<SysAgent> agentList;
        List<SysLvRate> levelList;

        for (SysDeptEntity sysDeptEntity : list) {
            agentList = agentService.queryNormalAgentList(sysDeptEntity.getDeptId());
            levelList = sysLevelRateService.queryLvList(sysDeptEntity.getDeptId());
            //根据渠道id修改
            updateLevelEveryMonth(sysDeptEntity, agentList, levelList);
        }
        logger.info("===============更新合伙人等级定时器关==============");
    }


    public void updateLevelEveryMonth(SysDeptEntity sysDeptEntity, List<SysAgent> agentList, List<SysLvRate> levelList) {

        logger.info("============更新" + sysDeptEntity.getName() + "合伙人等级中==========");

        switch (sysDeptEntity.getDeptId().intValue()) {
            //百易和卡一共用一套
            case 1:
            case 889323:
                for (SysAgent agent : agentList) {
                    baiYiUpdateLevel(agent, levelList, false);
                }
                break;
            //信创,考拉，星脉一套
            case 889324:
            case 889326:
            case 5:
                for (SysAgent agent : agentList) {
                    xinChuangUpdateLevel(agent, levelList, false);
                }
                break;
            default:
                logger.info("========" + sysDeptEntity.getName() + "合伙人等级未更新==========");
                break;
        }


        logger.info("========" + sysDeptEntity.getName() + "合伙人等级更新完==========");
    }


    /**
     * 信创的规则
     *
     * @param sysAgent
     * @param levelList
     * @param flag
     */
    private void xinChuangUpdateLevel(SysAgent sysAgent, List<SysLvRate> levelList, boolean flag) {
        //交易总额
        BigDecimal amount;
        //类型
        Integer type = sysAgent.getType();
        //判断合伙人当前是否存在记录，存在则修改，不存在则添加
        SysAgentGrade sysAgentGrade = agentGradeService.checkByAgentId(sysAgent.getAgentId());

        amount = transactionInfoService.queryLMonthTranSum(sysAgent.getAgentId());
        //核算是否需要锁死等级
        if (checkLockedLv(sysAgent, amount, sysAgentGrade)) {
            return;
        }
        //不存在则新增
        if (sysAgentGrade == null) {
            flag = true;
            sysAgentGrade = new SysAgentGrade();
            sysAgentGrade.setAgentId(sysAgent.getAgentId());
        }

        //信创的v9达标金额
        BigDecimal V9_Amount = levelList.get(8).getMinTurnover();
        //翻一万倍
        V9_Amount = V9_Amount.multiply(MULTINUM);
        int result = amount.compareTo(V9_Amount);

        //判断盟主或一次性交易300台的合伙人交易量是否大于V9要求，无则V9，有则正常计算
        if ((type == 4 || type == 3) && result == -1) {

            sysAgentGrade.setThisGrade(9);
            sysAgentGrade.setUpdateTime(new Date());
            sysAgentGrade.setUpperGrade(flag ? 0 : sysAgentGrade.getThisGrade());
        } else {
            //判断交易量，更新等级
            updateGradeByLvRate(levelList, flag, amount, sysAgentGrade);
        }
        addSysAgentGrade(sysAgent, flag, sysAgentGrade);
    }

    /**
     * 检查锁定等级是否达标 ,未达标则锁死等级
     *
     * @param sysAgent
     * @param amount
     * @param sysAgentGrade
     * @return
     */
    private boolean checkLockedLv(SysAgent sysAgent, BigDecimal amount, SysAgentGrade sysAgentGrade) {
        if (sysAgentGrade != null) {
            if (sysAgentGrade.getLocked().intValue() == 1) {
                SysLvRate temp = sysLevelRateService.queryRate(sysAgent.getAgentId(), sysAgent.getDeptId(), 1, "否");
                BigDecimal maxTran = temp.getMaxTurnover();
                maxTran = maxTran.multiply(MULTINUM);
                if (maxTran.compareTo(amount) == 1) {
                    return true;
                }
            }
        }
        return false;
    }

    private void updateGradeByLvRate(List<SysLvRate> levelList, boolean flag, BigDecimal amount, SysAgentGrade sysAgentGrade) {
        SysLvRate sysLevelRate;
        Integer minResult;
        Integer maxResult;
        for (int j = 0; j < levelList.size(); j++) {
            sysLevelRate = levelList.get(j);
            //月结余和当前等级达标最小值的对比 1：大于 0：等于 -1小于
            minResult = amount.compareTo(sysLevelRate.getMinTurnover().multiply(MULTINUM));
            //月结余和当前等级达标最大值的对比
            maxResult = amount.compareTo(sysLevelRate.getMaxTurnover().multiply(MULTINUM));
            //最后一次判断，只需要判断是否最后一次
            if (j == levelList.size() - 1) {
                sysAgentGrade.setUpperGrade(flag ? 0 : sysAgentGrade.getThisGrade());
                //更新本月等级
                sysAgentGrade.setThisGrade(sysLevelRate.getLv());
                sysAgentGrade.setUpdateTime(new Date());
                break;
            }
            //最小值 <= 交易量 < 最大值
            if ((minResult == 1 || minResult == 0) && maxResult == -1) {
                //将本月等级给上个月
                sysAgentGrade.setUpperGrade(flag ? 0 : sysAgentGrade.getThisGrade());
                //更新本月等级
                sysAgentGrade.setThisGrade(sysLevelRate.getLv());
                sysAgentGrade.setUpdateTime(new Date());
                break;
            }
        }
    }


    /**
     * 百易合伙人的规则
     */
    private void baiYiUpdateLevel(SysAgent sysAgent, List<SysLvRate> levelList, boolean flag) {

        BigDecimal amount;//交易总额
        //类型
        Integer type = sysAgent.getType();
        //判断合伙人当前是否存在记录，存在则修改，不存在则添加
        SysAgentGrade sysAgentGrade = agentGradeService.checkByAgentId(sysAgent.getAgentId());
        amount = transactionInfoService.queryLMonthTranSum(sysAgent.getAgentId());
        //核算是否需要锁死等级
        if (checkLockedLv(sysAgent, amount, sysAgentGrade)) {
            return;
        }

        //不存在则新增
        if (sysAgentGrade == null) {
            flag = true;
            sysAgentGrade = new SysAgentGrade();
            sysAgentGrade.setAgentId(sysAgent.getAgentId());
        }

        BigDecimal baiyi_V7_Amount = levelList.get(6).getMinTurnover();
        //翻一万倍
        baiyi_V7_Amount = baiyi_V7_Amount.multiply(MULTINUM);
        int V7result = amount.compareTo(baiyi_V7_Amount);

        BigDecimal baiyi_V5_Amount = levelList.get(4).getMinTurnover();
        //翻一万倍
        baiyi_V5_Amount = baiyi_V5_Amount.multiply(MULTINUM);
        int V5result = amount.compareTo(baiyi_V5_Amount);
        //一次性交易300台的合伙人且交易量不达到v5的直接v5
        if (type == 4 && V5result == -1) {
            sysAgentGrade.setThisGrade(5);
            sysAgentGrade.setUpdateTime(new Date());
            sysAgentGrade.setUpperGrade(flag ? 0 : sysAgentGrade.getThisGrade());
            //判断盟主交易量是否大于V7要求，无则V7，有则正常计算
        } else if (type == 3 && V7result == -1) {
            sysAgentGrade.setThisGrade(7);
            sysAgentGrade.setUpdateTime(new Date());
            sysAgentGrade.setUpperGrade(flag ? 0 : sysAgentGrade.getThisGrade());
        } else {
            updateGradeByLvRate(levelList, flag, amount, sysAgentGrade);
        }
        addSysAgentGrade(sysAgent, flag, sysAgentGrade);
    }

    private void addSysAgentGrade(SysAgent sysAgent, boolean flag, SysAgentGrade sysAgentGrade) {
        if (flag) {
            agentGradeService.insertAgentGrade(sysAgentGrade);
            logger.info("=======新增了一条信息，合伙人Id为" + sysAgent.getAgentId() + "=等级为：=" + sysAgentGrade.getThisGrade() + "=============");
        } else {
            agentGradeService.updateAgentGrade(sysAgentGrade);
            logger.info("=======修改了一条信息，合伙人Id为" + sysAgent.getAgentId() + "=等级为：=" + sysAgentGrade.getThisGrade() + "============");
        }
    }

}
